const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const speechService = require('../services/azure/speechService');

// 确保上传目录存在
const uploadDir = 'public/uploads/audio';
if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir, { recursive: true });
}

// 配置音频文件上传
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'public/uploads/audio');
    },
    filename: function (req, file, cb) {
        cb(null, 'speech-' + Date.now() + path.extname(file.originalname));
    }
});

const upload = multer({ storage: storage });

// 通用语音识别接口 - 自动识别中英文
router.post('/recognize', upload.single('audio'), async (req, res) => {
    try {
        if (!req.file) {
            return res.status(400).json({
                success: false,
                message: '请上传音频文件'
            });
        }

        console.log('Uploaded file:', req.file);
        // 不指定语言，让 Azure 自动识别
        const result = await speechService.speechToText(req.file);
        
        return res.json(result);
    } catch (error) {
        console.error('Speech recognition error:', error);
        return res.status(500).json({
            success: false,
            message: '语音识别失败: ' + error.message
        });
    }
});

// 文本转语音接口
router.post('/synthesize', async (req, res) => {
    try {
        const { text, voiceName } = req.body;

        // 验证请求参数
        if (!text) {
            return res.status(400).json({
                success: false,
                message: '请提供要转换的文本'
            });
        }

        // 调用 TTS 服务
        const result = await speechService.textToSpeech(text, voiceName);
        
        return res.json(result);
    } catch (error) {
        console.error('Text-to-speech error:', error);
        return res.status(500).json({
            success: false,
            message: '文本转语音失败: ' + error.message
        });
    }
});

// 文本转语音接口（流式传输）
router.post('/synthesize/stream', async (req, res) => {
    try {
        const { text, voiceName } = req.body;

        // 验证请求参数
        if (!text) {
            return res.status(400).json({
                success: false,
                message: '请提供要转换的文本'
            });
        }

        // 调用流式 TTS 服务
        const audioBuffer = await speechService.textToSpeechStream(text, voiceName);
        
        // 设置响应头
        res.set({
            'Content-Type': 'audio/wav',
            'Content-Length': audioBuffer.length
        });

        // 发送音频数据
        res.send(audioBuffer);
    } catch (error) {
        console.error('Text-to-speech stream error:', error);
        res.status(500).json({
            success: false,
            message: '文本转语音失败: ' + error.message
        });
    }
});

module.exports = router; 